package org.snowin.utils;


import java.io.File;
import java.util.*;


import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.snowin.common.InitWebDriver;
import org.snowin.common.SessionData;

public class IdentifyCode {
    String manageHost;
    SessionData sessionData;
    WebDriver webDriver;
    String hostName = "";
    Logger logger;
    WebDriver newDriver;
    String sp = System.getProperty("file.separator");

    public IdentifyCode(SessionData sessionData) {
        this.sessionData = sessionData;
        this.webDriver = sessionData.getWebDriver();
        this.hostName = sessionData.getHostName();
        this.logger = sessionData.getLogger();
        this.manageHost = this.hostName.replace("www", "manage");
        openNewWebDrvier();
        loginToManage();
    }

    public String getPicCodeVaule(String bid) {
        this.sessionData.getLogger().info("~~~~~~~~~~~~Start to get the picture verification code  ~~~~~~~~~~~~");
        String result = "";
        try {
            Set<Cookie> allCookies = this.sessionData.getWebDriver().manage().getCookies();
            String guid = "";
            for (Cookie loadedCookie : allCookies) {
                if (loadedCookie.getName().equalsIgnoreCase("guid")) {
                    guid = loadedCookie.getValue();
                }
            }
            String requestUrl = this.manageHost;

            this.newDriver.get(requestUrl);
            WebElement userName = this.newDriver.findElement(
                    By.tagName("body"));
            result = userName.getText();
            this.sessionData
                    .getLogger()
                    .info("~~~~~~~~~~~~Finish to get the picture verification code  ~~~~~~~~~~~~");
        } catch (Exception e) {
            this.sessionData.getLogger().error("~~~~~~~~~~~~【  error 】 Get the picture verification code failed! ~~~~~~~~~~~~");
            e.printStackTrace();
        }
        closeNewWebDrvier();
        return result;
    }

    public String getSmsCodeVaule(String phoneNum, String bid) {
        this.sessionData.getLogger().info("~~~~~~~~~~~~Start to get the picture verification code  ~~~~~~~~~~~~");
        String result = "";
        try {
            String guid = phoneNum;
            String requestUrl = this.manageHost;
            this.newDriver.get(requestUrl);
            WebElement userName = this.newDriver.findElement(
                    By.tagName("body"));
            result = userName.getText();
            this.sessionData
                    .getLogger()
                    .info("~~~~~~~~~~~~Finish to get the picture verification code  ~~~~~~~~~~~~");
        } catch (Exception e) {
            this.sessionData.getLogger().error("~~~~~~~~~~~~【  error 】 Get the picture verification code failed! ~~~~~~~~~~~~");
            e.printStackTrace();
        }
        closeNewWebDrvier();
        return result;
    }

    public void loginToManage() {
        this.newDriver.get(this.manageHost);
        boolean isLogin = false;
        List<WebElement> el = new ArrayList();
        try {
            el = this.newDriver.findElements(By.linkText("退出"));
            isLogin = el.size() >= 1;
        } catch (Exception e) {
            isLogin = false;
        }
        if (!isLogin) {
            try {
                WebElement userName = this.newDriver.findElement(
                        By.name("username"));
                userName.sendKeys(new CharSequence[]{"hekun"});
                WebElement passwd = this.newDriver.findElement(
                        By.name("password"));
                passwd.sendKeys(new CharSequence[]{"123456"});
                WebElement submitBt = this.newDriver.findElement(
                        By.name("submit"));
                submitBt.click();
            } catch (Exception e) {
                this.logger.error("~~~~~~~~~~~~~~ Login to manage failed! ~~~~~~~~~~~~");
                this.logger.info("Exception", e);
            }
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                this.logger.error("~~~~~~~~~~~~ Log to manage failed! ~~~~~~~~~~~~");
                e.printStackTrace();
            }
        }
    }

    private void closeNewWebDrvier() {
        this.newDriver.close();
        this.newDriver.quit();
    }

    private void openNewWebDrvier() {
        SAXReader saxReader = new SAXReader();
        Document doc = null;
        HashMap<String, String> webDriverhash = new HashMap();
        HashMap<String, String> newWebDriverHash = new HashMap();
        try {
            String sp = System.getProperty("file.separator");
            doc = saxReader.read(new File(GlobalInfo.rootPath + sp + "config" + sp + "conf" + sp + "wtd.cfg.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        List<Element> webDriveEles = doc.selectNodes("//Browser/*");
        for (Element e : webDriveEles) {
            String location = "";
            location = e.attributeValue("location");
            String browserName = e.getName();
            webDriverhash.put(browserName, location);
        }
        String frontWebDriverName = this.webDriver.toString();
        Iterator iter = webDriverhash.entrySet().iterator();
        String webDriverKey = "";
        String browserName = "";
        String browserLocation = "";
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String sp = System.getProperty("file.separator");
            browserName = (String) entry.getKey();
            browserLocation = (String) entry.getValue();
            if (frontWebDriverName.toLowerCase().contains(browserName.toLowerCase())) {
                break;
            }
        }
        this.newDriver = new InitWebDriver().initWebDrvier(browserName, browserLocation);
    }
}
